/**
 * 
 */
package org.dg.iag.server;

import org.dg.iag.entity.LoginRequest;
import org.dg.iag.entity.LoginStatus;
import org.dg.iag.util.ApplicationConstants;
import org.dg.iag.util.LoginUtil;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.Cookie;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
import org.restlet.util.Series;

/**
 * @author Alex Gartner
 *
 */
public class LoginServerResource extends ServerResource {
	
	@Get
	public LoginStatus getLoginStatus() {
		Request req		= this.getRequest();
		Series<Cookie> cookies = req.getCookies();
		String username		= cookies.getValues(ApplicationConstants.COOKIE_USERNAME);
		String sessionid	= cookies.getValues(ApplicationConstants.COOKIE_SESSIONID);
		LoginStatus ls 		= new LoginStatus(false, "","Not logged in");
		if ( LoginUtil.checkLogin(username, sessionid) ) {
			ls.setUsername(username);
			ls.setLoggedIn(true);
			ls.setMessage("OK");
		}
		return ls;
	}
	@Post 
	public LoginStatus login(LoginRequest lr) {
		if ( lr != null && "logout".equals(lr.getAction()) ) {
			String username	= this.getRequest().getCookies().getFirstValue(ApplicationConstants.COOKIE_USERNAME);
			LoginUtil.logout(username);
			LoginStatus ls 		= new LoginStatus(false, username,"Logged out");
			return ls;
		}
		
		//LOGIN
		LoginStatus ls 		= new LoginStatus(false, "","Wrong username or password");
		if ( lr.getUsername() != null && lr.getUsername().length() > 0 && 
				lr.getMd5Password() != null && lr.getMd5Password().length() > 0 ) {
			String sessionid	= LoginUtil.login(lr.getUsername(), lr.getMd5Password() );
			if ( sessionid != null  ) {
				ls.setLoggedIn(true);
				ls.setMessage("OK");
				ls.setUsername(lr.getUsername());
				Response resp	= this.getResponse();
				resp.getCookieSettings().add(ApplicationConstants.COOKIE_USERNAME, lr.getUsername() );
				resp.getCookieSettings().add(ApplicationConstants.COOKIE_SESSIONID, sessionid );
			}
		}
		return ls;
	}
}
